import os
from PIL import Image, ImageOps
import io
import subprocess
from concurrent.futures import ThreadPoolExecutor
import logging

# 创建第一个 Logger 对象，记录到 example.log
logger_example = logging.getLogger('error_logger')
logger_example.setLevel(logging.INFO)
file_handler_example = logging.FileHandler('error_logger.log')
file_handler_example.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(message)s')
file_handler_example.setFormatter(formatter)
logger_example.addHandler(file_handler_example)

# 创建第二个 Logger 对象，记录到 another.log
logger_another = logging.getLogger('sucesse_logger')
logger_another.setLevel(logging.INFO)
file_handler_another = logging.FileHandler('sucesse_logger.log')
file_handler_another.setLevel(logging.INFO)
file_handler_another.setFormatter(formatter)
logger_another.addHandler(file_handler_another)

optipng = './optipng.exe'
print('开始')
target_size = 400 * 1024  # 400 KB
max_workers = 5
def compress_image(image_path, target_size):
    try:
        with open(image_path, 'rb') as f:
            img = Image.open(f)
            ext = os.path.splitext(image_path)[1].lower()

            if ext == '.jpg' or ext == '.jpeg':
                img = img.convert('RGB')
                output_io_stream = io.BytesIO()
                img.save(output_io_stream, format='JPEG', optimize=True, quality=80)
                compressed_image = output_io_stream.getvalue()

            elif ext == '.png':
                temp_file = image_path + '.png'
                img.save(temp_file, format='PNG', optimize=True)
                subprocess.run(['optipng', f'-o3', temp_file])

                with open(temp_file, 'rb') as f:
                    optimized_png = f.read()
                compressed_image = optimized_png

                os.remove(temp_file)
            else:
                raise ValueError(f"Unsupported image format: {ext}")

            if len(compressed_image) <= target_size:
                with open(image_path, 'wb') as f:
                    f.write(compressed_image)
                # 获取压缩后的文件大小（单位：字节）
                compressed_size = os.path.getsize(image_path)
                # 将字节转换为 KB，并记录日志
                compressed_size_kb = compressed_size // 1024
                print(f"压缩成功： {image_path} to {compressed_size_kb} bytes")
                logger_another.info('压缩成功后的路径：%s，大小：%s KB', image_path, compressed_size_kb)
            else:
                # convert input.png -resize 90% output.png
                with open(image_path, 'wb') as f:
                    f.write(compressed_image)
                    resize_image(image_path, 0.9)  # 调整为90%大小

    except Exception as e:
        print(f"Error compressing {image_path}: {str(e)}")
        logger_example.info('失败后的路径：%s', image_path)

def resize_image(image_path, img_size):
    original_image = Image.open(image_path)
    width, height = original_image.size
    print('原始图像尺寸:', width, height)
    # 使用ANTIALIAS方法进行缩小，保持较好的质量0
    resized_width = int(original_image.size[0] * img_size)  # 缩小到原始宽度的80%
    resized_height = int(original_image.size[1] * img_size)  # 缩小到原始高度的80%
    resized_image = original_image.resize((resized_width, resized_height), Image.LANCZOS)
    resized_image.save(image_path)
    if os.path.getsize(image_path) >= 500*1024:
        resize_image(image_path,img_size)
    else:
        print('调整大小后的图像尺寸:', resized_image.size)
        # 获取压缩后的文件大小（单位：字节）
        compressed_size = os.path.getsize(image_path)
        # 将字节转换为 KB，并记录日志
        compressed_size_kb = compressed_size // 1024
        logger_another.info('图片等比缩小后的路径：%s，大小：%s KB', image_path, compressed_size_kb)
        return





def find_and_compress_images(directory, target_size, max_workers):
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        for root, dirs, files in os.walk(directory):
            for file in files:
                file_path = os.path.join(root, file)
                #检查文件大小
                if os.path.getsize(file_path) > target_size:
                    executor.submit(compress_image, file_path, target_size)
                    print(f"开始压缩：{file_path}")


find_and_compress_images('C:\\Users\\Administrator\\Desktop\\Themes', target_size, max_workers)


